package com.peng.community.config.advice;

import com.peng.community.util.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice(annotations = Controller.class)
@Slf4j
public class ExceptionAdvice {

//    @ExceptionHandler({Exception.class})
//    public void handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
//        //日志记录异常信息
//        log.error("服务器发生异常:{}", e.getMessage());
//        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
//            log.error(stackTraceElement.toString());
//        }
//
//        //根据当前请求类型做相应处理
//        String requestType = request.getHeader("x-request-with");
//        if ("XmlHttpRequest".equals(requestType)) {
//            //当前请求为异步请求，响应json数据
//            //响应普通字符串，由页面转为json
//            response.setContentType("text/plain;charset=utf-8");
//            response.getWriter().write(CommunityUtils.toJsonString(1,"服务器发生异常"));
//        } else {
//            //普通请求，响应错误页面
//            response.sendRedirect(request.getContextPath() + "/error");
//        }
//    }
}
